import xmind


def gen_xmind_by_json(parent, data):
    if data is None:
        return
    node = parent.addSubTopic()
    for key in data:
        if key == 'title':
            node.setTitle(data['title'])
        elif key == 'topic':
            gen_xmind_by_json(node, data['topic'])
        elif key == 'children':
            if isinstance(data['children'], dict):
                gen_xmind_by_json(node, data['children'])
            elif isinstance(data['children'], list):
                for i in range(len(data['children'])):
                    gen_xmind_by_json(node, data['children'][i])


def gen_xmind(file_path, json_data):
    workbook = xmind.load("temp.xmind")
    sheet = workbook.getPrimarySheet()
    root = sheet.getRootTopic()
    root.setStructureClass("org.xmind.ui.logic.right")
    gen_xmind_by_json(root, json_data)
    xmind.save(workbook, path=file_path)
    print(f"成功保存文件: {file_path}")

